<template>
  <div class="SearchForm">
    <a-form layout="inline" :model="props.formModel" ref="searchForm">
      <a-form-item
        v-for="(item, index) in props.items"
        :key="index"
        :label="item.label"
        :name="item.field"
        :class="item.class"
      >
        <slot
          :name="item.slot"
          v-bind="item.props"
          v-if="item.component === 'slot'"
          :model="props.formModel"
        ></slot>
        <component
          v-else
          :is="getComponent(item.component)"
          v-bind="getComponentProps(item)"
          v-model:value="props.formModel[item.field]"
        />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button @click="onSearch" type="primary">查询</a-button>
          <a-button @click="onReset">重置</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>
<script setup>
  import {
    Input,
    InputNumber,
    Select,
    DatePicker,
    Radio,
    Cascader,
    TimePicker,
    RangePicker,
  } from 'ant-design-vue';
  const componentMap = {
    Input,
    InputNumber,
    Select,
    DatePicker,
    Radio,
    Cascader,
    TimePicker,
    RangePicker,
  };
  const getComponent = (component) => {
    return componentMap[component];
  };
  const props = defineProps({
    items: {
      type: Array,
      default: () => [],
    },
    formModel: {
      type: Object,
      default: () => {},
    },
  });
  const emit = defineEmits(['onSearch', 'onReset']);

  const searchForm = ref(null);

  const getComponentProps = (item) => {
    return {
      style: 'width:250px',
      allowClear: true,
      placeholder: createPlaceholder(item),
      ...item.props,
    };
  };

  const createPlaceholder = ({ component, label }) => {
    let placeholder = undefined;
    if (component === 'Input' || component === 'InputNumber') placeholder = '请输入' + label;
    if (
      ['Picker', 'Select', 'Checkbox', 'Radio', 'Switch', 'DatePicker', 'TimePicker'].includes(
        component
      )
    ) {
      placeholder = '请选择' + label;
    }
    return placeholder;
  };
  //点击查询
  const onSearch = () => {
    emit('onSearch', props.formModel);
  };
  //点击重置
  const onReset = () => {
    searchForm.value.resetFields();
    emit('onReset');
  };
</script>

<style lang="less" scoped>
  .SearchForm {
    .ant-form-item {
      margin-bottom: 20px;
    }
  }
</style>
